# Make turnout table - does VBM increase overall turnout?
# Note: this is preliminary analysis. we include only the states for which
#       we have 2020 returns (UT, NV, MT, VT).
# By Dom Valentino and Chris Kenny
# libs --------------------------------------------------------------------
library(tidyverse) # select(), mutate(), pivot_longer()
library(lfe) # felm()
library(xtable) # xtable()

# data --------------------------------------------------------------------
data <- read.csv(file = '../data/analysis/analysis.csv') %>% 
  filter(state %in% c("UT", "WA", "CA")) # restrict analysis to thompson et al. states

# make col 1
m1 <- felm(turnout_share ~ treat | county_id + state_year_id | 0 | county_id, data = data) # no county trends
b1 <- round(m1$coefficients[1], 3) # beta
se1 <- round(m1$cse[1], 3) # standard error
n1 <- m1$N # number of observations
nc1 <- length(levels(m1$fe$county_id)) # number of counties
ne1 <- length(levels(m1$fe$state_year_id)) # number of elections

# make col 2
temp <- data %>% mutate(county_id = as.factor(county_id), year = as.numeric(year))
m2 <- felm(turnout_share ~ treat | county_id + county_id:year + state_year_id | 0 | county_id, data = temp) # linear county trends. this takes a minute because of county_id:year interaction
b2 <- round(m2$coefficients[1], 3)
se2 <- round(m2$cse[1], 3)
n2 <- m2$N
nc2 <- length(levels(m2$fe[["year:county_id"]]))
ne2 <- length(levels(m2$fe$state_year_id))

# build table
tbl <- tibble(" " = c("VBM", "", "# Counties", "# Elections","# Obs", "County FE", "State by Year FE", "County Trends"),
              "(1)" = c(b1, paste0("(", se1, ")"), nc1, ne1, n1, "Yes", "Yes", "No"),
              "(2)" = c(b2, paste0("(", se2, ")"), nc2, ne2, n2, "Yes", "Yes", "Linear"))
x <- xtable(tbl, caption = "\\textbf{Vote-by-Mail Expansion Increases Participation.}", label = "tab:turnout_effects_orig")
align(x) <- c("l", "l", rep("c", 2))
print(x, file = "../exhibits/turnout_table_original_states.tex", compress = F, hline.after = c(-1, -1, 0, 5), hline.before = 1,
      include.rownames = F, include.colnames = F, caption.placement = "top",
      add.to.row = list(pos = list(0, 0, nrow(tbl)), command = c("& \\multicolumn{2}{c}{\\hspace{-3em}Dem Vote Share [0-1]} \\\\\n",
                                                                 "& (1) & (2) \\\\\n",
                                                                 "\\hline\\hline\\multicolumn{3}{l}{\\footnotesize{Robust standard errors clustered by county in parentheses.}} \\\\\n")))
